package com.community.owner.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

import com.community.owner.domain.User;
import com.community.owner.domain.vo.OwnerAddRequest;
import com.community.owner.domain.vo.OwnerVo;
import com.community.owner.mapper.OwnerHouseMapper;
import com.community.owner.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.community.owner.mapper.OwnerMapper;
import com.community.owner.domain.Owner;
import com.community.owner.service.OwnerService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 业主信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-10-25
 */
@Service
@Slf4j
public class OwnerServiceImpl implements OwnerService
{
    @Autowired
    private OwnerMapper ownerMapper;

    /**
     * 查询业主信息
     * 
     * @param ownerId 业主信息主键
     * @return 业主信息
     */
    @Override
    public Owner selectOwnerByOwnerId(Long ownerId)
    {
        return ownerMapper.selectOwnerByOwnerId(ownerId);
    }

    /**
     * 查询业主信息列表
     * 
     * @param owner 业主信息
     * @return 业主信息
     */
    @Override
    public List<Owner> selectOwnerList(Owner owner)
    {
        return ownerMapper.selectOwnerList(owner);
    }

    /**
     * 新增业主信息
     * 
     * @param owner 业主信息
     * @return 结果
     */
    @Override
    public int insertOwner(Owner owner)
    {
        return ownerMapper.insertOwner(owner);
    }

    /**
     * 修改业主信息
     * 
     * @param owner 业主信息
     * @return 结果
     */
    @Override
    public int updateOwner(Owner owner)
    {
        return ownerMapper.updateOwner(owner);
    }

    /**
     * 批量删除业主信息
     * 
     * @param ownerIds 需要删除的业主信息主键
     * @return 结果
     */
    @Override
    public int deleteOwnerByOwnerIds(Long[] ownerIds)
    {
        return ownerMapper.deleteOwnerByOwnerIds(ownerIds);
    }

    /**
     * 删除业主信息信息
     * 
     * @param ownerId 业主信息主键
     * @return 结果
     */
    @Override
    public int deleteOwnerByOwnerId(Long ownerId)
    {
        return ownerMapper.deleteOwnerByOwnerId(ownerId);
    }


    @Override
    public Owner selectOwnerWithDetailsByOwnerId(Long ownerId) {
        return ownerMapper.selectOwnerWithDetailsByOwnerId(ownerId);
    }

    @Override
    public Long count() {
        return ownerMapper.count();
    }


    @Override
    public List<OwnerVo> selectOwnerVoList(OwnerVo ownerVo) {
        return ownerMapper.selectOwnerVoList(ownerVo);
    }


    @Override
    public Integer addPermsByFile(List<Owner> ownerList) {
        return ownerMapper.addPermsByFile(ownerList);
    }

    @Autowired
    private OwnerHouseMapper ownerHouseMapper;
    @Autowired
    private UserMapper userMapper;
    @Override
    @Transactional
    public Integer addOwnerWithUser(OwnerAddRequest request) {
        // 1. 检查手机号是否已存在
        if (userMapper.checkPhoneNumberExists(request.getPhonenumber()) > 0) {
            throw new RuntimeException("手机号已存在");
        }
        // 1. 检查姓名是否已存在
        if (userMapper.checkUserNameExists(request.getUserName()) > 0) {
            throw new RuntimeException("业主姓名已存在");
        }

        // 2. 创建 sys_user 记录
        User user = new User();
        user.setUserName(request.getUserName());
        user.setPhonenumber(request.getPhonenumber());
        user.setNickName(request.getUserName());
        // 添加try-catch包围用户插入
         userMapper.insertUser(user);

        // 3. 创建 owner 记录
        Owner owner = new Owner();

        // 设置业主基本信息
        owner.setUserId(user.getUserId());
        owner.setOwnerType(request.getOwnerType());
        owner.setIdCard(request.getIdCard());
        owner.setGender(request.getGender());
        //日期格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            owner.setBirthDate(sdf.parse(request.getBirthDate()));
        } catch (ParseException e) {
            throw new RuntimeException("出生日期格式错误，应为 yyyy-MM-dd 格式", e);
        }
        owner.setNation(request.getNation());
        owner.setMaritalStatus(request.getMaritalStatus());
        owner.setHouseholdType(request.getHouseholdType());
        owner.setCurrentAddress(request.getCurrentAddress());
        owner.setEmergencyContactName(request.getEmergencyContactName());
        owner.setEmergencyContactRelation(request.getEmergencyContactRelation());
        owner.setEmergencyContactPhone(request.getEmergencyContactPhone());

        // 设置房屋关联信息
        owner.setHouseId(request.getHouseId());
        owner.setRoomNo(request.getRoomNo());
        try {
            int ownerResult = ownerMapper.insertOwnerAddRequest(owner);
            log.info("业主插入执行完成，影响行数: {}", ownerResult);

            if (ownerResult <= 0) {
                log.error("业主插入失败，影响行数为: {}", ownerResult);
                throw new RuntimeException("业主信息插入失败，影响行数: " + ownerResult);
            }

            log.info("=== 业主添加成功，用户ID: {}, 业主ID: {} ===", user.getUserId(), owner.getOwnerId());
            return ownerResult;

        } catch (Exception e) {
            log.error("业主插入过程中出现异常: ", e);
            throw new RuntimeException("业主信息插入失败: " + e.getMessage(), e);
        }
    }
}
